package mission_tour.solution;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class tour_coupon_info extends Activity implements ServerIp{
    /** Called when the activity is first created. */
    Bitmap c_img;
    AlertDialog.Builder nologin;
    ProgressDialog insert_coupon_no;
    int c_no;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_coupon_info);
        
        TextView info_shopname_text = (TextView) findViewById(R.id.info_shopname_text);
		TextView info_shopaddress_text = (TextView) findViewById(R.id.info_shopaddress_text);
		TextView info_shoptel_text = (TextView) findViewById(R.id.info_shoptel_text);
		
		TextView s_menu_text = (TextView) findViewById(R.id.s_menu_text);
		TextView s_hours_text = (TextView) findViewById(R.id.s_hours_text);
		TextView s_holyday_text = (TextView) findViewById(R.id.s_holyday_text);
		
		TextView coupon_subject_text = (TextView) findViewById(R.id.coupon_subject_text);
		TextView coupon_servicelife_text = (TextView) findViewById(R.id.coupon_servicelife_text);
		TextView coupon_matter_text = (TextView) findViewById(R.id.coupon_matter_text);
			
		ImageView coupon_img = (ImageView) findViewById(R.id.coupon_img);
        
        URLConnection conn = null;
		InputStream is= null;
		
        URL imageURL;
		try {
			imageURL = new URL(items.coupon_list.get(items.coupon_position).getImglink());
			conn = imageURL.openConnection();
			conn.connect();
			is = conn.getInputStream();
 
			BufferedInputStream bis = new BufferedInputStream(is);
			c_img = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			
			coupon_img.setImageBitmap(c_img);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		info_shopname_text.setText(items.coupon_list.get(items.coupon_position).getShopname());
		info_shopaddress_text.setText(items.coupon_list.get(items.coupon_position).getShopaddress());
		info_shoptel_text.setText(items.coupon_list.get(items.coupon_position).getShoptel());
		
		s_menu_text.setText("대표메뉴 : "+items.coupon_list.get(items.coupon_position).getShopmenu());
		s_hours_text.setText("영업시간 : "+items.coupon_list.get(items.coupon_position).getShophours());
		s_holyday_text.setText("휴 일 : "+items.coupon_list.get(items.coupon_position).getShopholyday());
		
		coupon_subject_text.setText(items.coupon_list.get(items.coupon_position).getCoupon_subject());
		coupon_servicelife_text.setText("사용기간 : "+items.coupon_list.get(items.coupon_position).getCoupon_servicelife());
		coupon_matter_text.setText("유의사항 : "+items.coupon_list.get(items.coupon_position).getCoupon_matters());
		
        LinearLayout couponinfo_coupon = (LinearLayout) findViewById(R.id.couponinfo_coupon);
        
        if(coupon_subject_text.getText().equals("coupon_off")){
        	couponinfo_coupon.setVisibility(0x00000008);
        }
        
        couponinfo_coupon.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub				
				if(items.coupon_info_back != 1){
					AlertDialog.Builder insert_mycopon = new AlertDialog.Builder(tour_coupon_info.this);
					insert_mycopon.setTitle(items.appname);
					insert_mycopon.setMessage("내 쿠폰함으로 담겠습니까?");
					insert_mycopon.setIcon(R.drawable.icon);
					insert_mycopon.setPositiveButton("네", new DialogInterface.OnClickListener(){
					@Override
						public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
							c_no = items.coupon_list.get(items.coupon_position).getCoupon_no();
							
							insert_coupon_no = ProgressDialog.show(tour_coupon_info.this,"","선택한 쿠폰을 담고 있습니다....",true);
							
							new Thread(new Runnable() {    
								@Override
								public void run() {
									URL zurl = null;
									String resultString =null;
									
									try {
									  	
										zurl = new URL(tour_mycoupon_insert+"?app_type="+items.apptype+"&c_code="+items.c_code+"&coupon_no="+c_no);
										
										HttpURLConnection httpz = (HttpURLConnection)zurl.openConnection();  
									
										BufferedReader inz = new BufferedReader(new InputStreamReader(httpz.getInputStream()));  
										StringBuffer bufferz = new StringBuffer();
											 
										int z;  
											 
										while((z=inz.read()) != -1){
											bufferz.append((char)z);
										}
											
										resultString= bufferz.toString().trim();
										
										if(resultString.trim().equals("1")){
											insert_coupon_no.cancel();
											
											runOnUiThread(new Runnable(){
											    @Override
											     public void run() {
											    	Toast.makeText(tour_coupon_info.this,"내 쿠폰함에 담기를 성공하였습니다",Toast.LENGTH_SHORT).show();
												}
											});
											Intent intent = new Intent(tour_coupon_info.this, tour_coupon.class);
											startActivityForResult(intent, 0);
											finish();
										}
										
									} catch (MalformedURLException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										runOnUiThread(new Runnable(){
										    @Override
										     public void run() {
										    	nologin = new AlertDialog.Builder(tour_coupon_info.this);
												nologin.setTitle(items.appname);
												nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
												nologin.setIcon(R.drawable.icon);
												nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
												@Override
													public void onClick(DialogInterface dialog, int which) {
													// TODO Auto-generated method stub
															moveTaskToBack(true);
															android.os.Process.killProcess(android.os.Process.myPid());
														}
													});
												nologin.show();
											}
										});
										e.printStackTrace();
									}
								}
						    }).start();
						}
					});
					insert_mycopon.setNeutralButton("아니오", null);
					insert_mycopon.show();	
				}
				return false;
			}
		});
    }
    public boolean onKeyDown( int KeyCode, KeyEvent event ){
		if( event.getAction() == KeyEvent.ACTION_DOWN ){
			if( KeyCode == KeyEvent.KEYCODE_BACK ){
				if(items.coupon_info_back != 0){
					Intent intent = new Intent(tour_coupon_info.this, tour_mycoupon.class);
					startActivityForResult(intent, 0);
					finish();
				}else{
					Intent intent = new Intent(tour_coupon_info.this, tour_coupon.class);
					startActivityForResult(intent, 0);
					finish();
				}
				
				
				return false;
			}
		}
		return super.onKeyDown(KeyCode, event);
	}
    public boolean onCreateOptionsMenu(Menu menu){
    	getMenuInflater().inflate(R.menu.quick, menu);
		return true;   	
    }

    public boolean onOptionsItemSelected(MenuItem item){
    	if(item.getItemId() == R.id.map_go){
    		startActivity(new Intent(this,tour_map.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.event_go){
    		startActivity(new Intent(this,tour_event_info.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.myinfo_go){
    		startActivity(new Intent(this,tour_myinfo.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.coupon_go){
    		startActivity(new Intent(this,tour_coupon.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.help_go){
    		startActivity(new Intent(this,tour_help.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.oxquiz_go){
    		items.event_list.removeAll(items.event_list);

    		new Thread(new Runnable() {    
				@Override
				public void run() {
					runOnUiThread(new Runnable(){
						 @Override
						 public void run() {
							 AlertDialog.Builder q_level = new AlertDialog.Builder(tour_coupon_info.this)
				    			.setTitle(items.appname)
				    			.setMessage("퀴즈 난이도를 선택해 주세요")
				    			.setIcon(R.drawable.icon)
				    			.setPositiveButton("초급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_coupon_info.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_easy);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_coupon_info.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_coupon_info.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			})
				    			.setNeutralButton("고급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_coupon_info.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_hard);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_coupon_info.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_coupon_info.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			});
								q_level.show();
						 }
					 });
				}
		    }).start();
    	}
		return false;
    }
}